from rest_framework.viewsets import ViewSet
from . import serializers,models
from utils.response import APIResponse
import re

# 多方式登录
class LoginViewSet(ViewSet):
    # 局部禁用认证、权限组件
    authentication_classes = ()
    permission_classes = ()
    def login(self,request,*args,**kwargs):
        serializer = serializers.LoginSerializer(data=request.data,context={'request':request})
        if serializer.is_valid():
            token = serializer.context.get('token')

            # 原来要一个个拿信息
            # username = serializer.context.get('username')
            # icon = serializer.context.get('icon')

            # 拿到登录用户，直接走序列化过程，将要返回给前台的数据直接序列化好给前台
            user = serializer.context.get('user')
            result = serializers.LoginSerializer(user,context={'request':request}).data
            result['token'] = token   #result --> id ,username,icon,token
            return APIResponse(result=result)
        return APIResponse(1,serializer.errors)

# 手机是否存在接口
class MobileViewSet(ViewSet):
    def check(self,request,*args,**kwargs):
        mobile = request.data.get('mobile',None)
        if not mobile:
            return APIResponse(1,'mobile field required')
        if not re.match(r'1[3-9][0-9]{9}$',mobile):
            return APIResponse(1,'mobile field error')
        try:
            models.User.objects.get(mobile=mobile)
            return APIResponse(result=True)  #手机号存在
        except:
            return APIResponse(result=False)  #手机号不存在


from libs import tx_sms
from django.core.cache import cache
from django.conf import settings
from .throttles import SMSRateThrottle
# 发送验证码接口
class SMSViewSet(ViewSet):
    # 设置频率限制，一个手机号一分钟只能访问一次
    throttle_classes = [SMSRateThrottle]

    def send(self,request,*args,**kwargs):
        # return APIResponse(result=False)
        # 1) 验证前台手机号验证手机格式
        mobile = request.query_params.get('mobile', None)  #get请求的数据从request.query_params中拿
        print(mobile)
        if not mobile:
            return APIResponse(1,'mobile field required')
        if not re.match(r'1[3-9][0-9]{9}$',mobile):
            return APIResponse(1,'mobile field error')
        # 2）后台产生短信验证码
        code = tx_sms.get_code()
        print(code)
        # 3）把验证码交给第三方，发送短信验证码信息
        result = tx_sms.send_code(mobile,code,settings.SMS_CACHE_TIME//60)
        print(result)
        # 4）如果短信发送成功，服务器缓存验证码（内存数据库），方便下一次校验
        if result:
            cache.set(settings.SMS_CACHE_KEY % {'mobile':mobile},code,settings.SMS_CACHE_TIME)
        # 5）响应前台短信是否发送成功
        return APIResponse(result=result)

# 手机验证码登录接口
class MobileLoginViewSet(ViewSet):
    # 局部禁用认证、权限组件
    authentication_classes = ()
    permission_classes = ()

    def login(self, request, *args, **kwargs):
        serializer = serializers.MobileLoginSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            token = serializer.context.get('token')
            # 拿到登录用户，直接走序列化过程，将要返回给前台的数据直接序列化好给前台
            user = serializer.context.get('user')
            # 返回给前台的数据结果 result --> id ,username,icon,token
            result = serializers.MobileLoginSerializer(user, context={'request': request}).data
            result['token'] = token
            return APIResponse(result=result)
        return APIResponse(1, serializer.errors)

# 手机验证码注册接口
from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins
class RegisterViewSet(GenericViewSet,mixins.CreateModelMixin):
    queryset = models.User.objects.all()
    serializer_class = serializers.RegisterSerializer
    def create(self, request, *args, **kwargs):
        response = super().create(request,*args,**kwargs)
        return APIResponse(result=response.data,http_status=response.status_code)







